/*
 * seth-main.c -- Network device example over Raw Sockets 
 *
 * Copyright (C) 2011 Saeedm <saeed.tx@gmail.com>
 *
 * The source code in this file can be freely used, adapted,
 * and redistributed in source or binary form, so long as an
 * acknowledgment appears in derived source files.  
 * No warranty is attached;
 * we cannot take responsibility for errors or fitness for use.
 *
 * $Id: seth-main.c,v 1.21 20011/10/1 02:36:03 Saeedm Exp $
 */

#include <linux/module.h>
#include <linux/init.h>
#include <linux/moduleparam.h>

#include <linux/sched.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/errno.h>  /* error codes */
#include <linux/types.h>  /* size_t */
#include <linux/interrupt.h> /* mark_bh */

#include <linux/in.h>
#include <linux/netdevice.h>   /* struct device, and other headers */
#include <linux/etherdevice.h> /* eth_type_trans */
#include <linux/net.h>         /* struct socket */
#include <linux/ip.h>          /* struct iphdr */
#include <linux/tcp.h>         /* struct tcphdr */
#include <linux/skbuff.h>

#include "seth.h"
#include "kraweth_data.h"
#include "krawsock.h"

#include <linux/in6.h>
#include <asm/checksum.h>

MODULE_AUTHOR("SaeedM - saeed.tx@gmail.com");
MODULE_LICENSE("Dual BSD/GPL");


static char* ifname="eth0";

module_param(ifname, charp, S_IRUGO);
//module_param(buffsize, int, S_IRUGO);

static int timeout = SETH_TIMEOUT;
module_param(timeout, int, 0);

/*
 * Do we run in NAPI mode?
 */
static int use_napi = 0;
module_param(use_napi, int, 0);


/*
 * A structure representing an in-flight packet.
*/ 
struct seth_packet {
	struct snull_packet *next;
	struct net_device *dev;
	int	datalen;
	u8 data[ETH_DATA_LEN];
};

struct seth_packet dummy_pkt;

int pool_size = 8;
module_param(pool_size, int, 0);

/*
 * This structure is private to each device. It is used to pass
 * packets in and out, so there is place for a packet
 */

struct seth_priv {
	struct net_device_stats stats;
	int status;
	//struct snull_packet *ppool;
	//struct snull_packet *rx_queue;  /* List of incoming packets */
	//int rx_int_enabled;
	//int tx_packetlen;
	//u8 *tx_packetdata;
	struct sk_buff *skb;
	spinlock_t lock;
	//int mtu;
	int ifindex;
	struct socket* sk;
};

static void seth_tx_timeout(struct net_device *dev);
static void (*seth_interrupt)(int, void *, struct pt_regs *);

/*
 * Set up a device's packet pool.
 
void snull_setup_pool(struct net_device *dev)
{
	struct snull_priv *priv = netdev_priv(dev);
	int i;
	struct snull_packet *pkt;

	priv->ppool = NULL;
	for (i = 0; i < pool_size; i++) {
		pkt = kmalloc (sizeof (struct snull_packet), GFP_KERNEL);
		if (pkt == NULL) {
			printk (KERN_NOTICE "Ran out of memory allocating packet pool\n");
			return;
		}
		pkt->dev = dev;
		pkt->next = priv->ppool;
		priv->ppool = pkt;
	}
}

void snull_teardown_pool(struct net_device *dev)
{
	struct snull_priv *priv = netdev_priv(dev);
	struct snull_packet *pkt;
    
	while ((pkt = priv->ppool)) {
		priv->ppool = pkt->next;
		kfree (pkt);
		// FIXME - in-flight packets ?
	}
}    
*/
/*
 * Buffer/pool management.

struct snull_packet *snull_get_tx_buffer(struct net_device *dev)
{
	struct snull_priv *priv = netdev_priv(dev);
	unsigned long flags;
	struct snull_packet *pkt;
    
	spin_lock_irqsave(&priv->lock, flags);
	pkt = priv->ppool;
	priv->ppool = pkt->next;
	if (priv->ppool == NULL) {
		printk (KERN_INFO "Pool empty\n");
		netif_stop_queue(dev);
	}
	spin_unlock_irqrestore(&priv->lock, flags);
	return pkt;
}


void snull_release_buffer(struct snull_packet *pkt)
{
	unsigned long flags;
	struct snull_priv *priv = netdev_priv(pkt->dev);
	
	spin_lock_irqsave(&priv->lock, flags);
	pkt->next = priv->ppool;
	priv->ppool = pkt;
	spin_unlock_irqrestore(&priv->lock, flags);
	if (netif_queue_stopped(pkt->dev) && pkt->next == NULL)
		netif_wake_queue(pkt->dev);
}

void snull_enqueue_buf(struct net_device *dev, struct snull_packet *pkt)
{
	unsigned long flags;
	struct snull_priv *priv = netdev_priv(dev);

	spin_lock_irqsave(&priv->lock, flags);
	//FIXME - misorders packets
	pkt->next = priv->rx_queue;  
	priv->rx_queue = pkt;
	spin_unlock_irqrestore(&priv->lock, flags);
}

struct snull_packet *snull_dequeue_buf(struct net_device *dev)
{
	struct snull_priv *priv = netdev_priv(dev);
	struct snull_packet *pkt;
	unsigned long flags;

	spin_lock_irqsave(&priv->lock, flags);
	pkt = priv->rx_queue;
	if (pkt != NULL)
		priv->rx_queue = pkt->next;
	spin_unlock_irqrestore(&priv->lock, flags);
	return pkt;
}
*/
/*
 * Enable and disable receive interrupts.
static void seth_rx_ints(struct net_device *dev, int enable)
{
	struct seth_priv *priv = netdev_priv(dev);
	priv->rx_int_enabled = enable;
}
 */

    
/*
 * Open and close
 */

int seth_open(struct net_device *dev)
{
	/* request_region(), request_irq(), ....  (like fops->open) */

	/* 
	 * Assign the hardware address of the board: use "\0SAEED", where
	 */
	KLOG("[%s] OPEN WAS CALLED\n",dev->name);
	netif_start_queue(dev);
	return 0;
}

int seth_release(struct net_device *dev)
{
    /* release ports, irq and such -- like fops->close */
	KLOG("[%s] CLOSE WAS CALLED",dev->name);

	netif_stop_queue(dev); /* can't transmit any more */
	return 0;
}

/*
 * Configuration changes (passed on by ifconfig)
 */
int seth_config(struct net_device *dev, struct ifmap *map)
{
	KLOG("[%s] CONFIG WAS CALLED",dev->name);
	if (dev->flags & IFF_UP) /* can't act on a running interface */
		return -EBUSY;

	/* Don't allow changing the I/O address */
	if (map->base_addr != dev->base_addr) {
		printk(KERN_WARNING "seth: Can't change I/O address\n");
		return -EOPNOTSUPP;
	}

	/* Allow changing the IRQ */
	if (map->irq != dev->irq) {
		dev->irq = map->irq;
        	/* request_irq() is delayed to open-time */
	}

	/* ignore other fields */
	return 0;
}

/*
 * Receive a packet: retrieve, encapsulate and pass over to upper levels
*/
void seth_rx(struct net_device *dev, struct seth_packet *pkt)
{
	struct sk_buff *skb;
	struct seth_priv *priv = netdev_priv(dev);
	
	//
	// The packet has been retrieved from the transmission
	// medium. Build an skb around it, so upper layers can handle it

	skb = dev_alloc_skb(pkt->datalen + 2);
	if (!skb) {
		if (printk_ratelimit())
			printk(KERN_NOTICE "snull rx: low on mem - packet dropped\n");
		priv->stats.rx_dropped++;
		goto out;
	}
	skb_reserve(skb, 2); 
	//align IP on 16B boundary 
	memcpy(skb_put(skb, pkt->datalen), pkt->data, pkt->datalen);

	//Write metadata, and then pass to the receive level
	skb->dev = dev;
	skb->protocol = eth_type_trans(skb, dev);
	skb->ip_summed = CHECKSUM_UNNECESSARY; //don't check it
	priv->stats.rx_packets++;
	priv->stats.rx_bytes += pkt->datalen;
	netif_rx(skb);
  out:
	return;
}
     

/*
 * The poll implementation.
 */
static int seth_poll(struct net_device *dev, int *budget)
{
//	int npackets = 0,quota = 0;
	
	//quota = min(dev->quota, *budget);
	/*struct sk_buff *skb;
	struct snull_priv *priv = netdev_priv(dev);
	struct snull_packet *pkt;
    
	while (npackets < quota && priv->rx_queue) {
		pkt = snull_dequeue_buf(dev);
		skb = dev_alloc_skb(pkt->datalen + 2);
		if (! skb) {
			if (printk_ratelimit())
				printk(KERN_NOTICE "snull: packet dropped\n");
			priv->stats.rx_dropped++;
			snull_release_buffer(pkt);
			continue;
		}
		skb_reserve(skb, 2); // align IP on 16B boundary 
		memcpy(skb_put(skb, pkt->datalen), pkt->data, pkt->datalen);
		skb->dev = dev;
		skb->protocol = eth_type_trans(skb, dev);
		skb->ip_summed = CHECKSUM_UNNECESSARY; // don't check it 
		netif_receive_skb(skb);
		
        	// Maintain stats 
		npackets++;
		priv->stats.rx_packets++;
		priv->stats.rx_bytes += pkt->datalen;
		snull_release_buffer(pkt);
	}
	// If we processed all packets, we're done; tell the kernel and reenable ints 
	*budget -= npackets;
	//dev->quota -= npackets;
	if (! priv->rx_queue) {
	 	//////netif_rx_complete(dev);
		snull_rx_ints(dev, 1);
		return 0;
	}
	*/
	/* We couldn't process everything. */
	return 1;
}
	    
        
/*
 * The typical interrupt entry point
 */
static void seth_regular_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	int statusword;
	struct seth_priv *priv;
//	struct seth_packet *pkt = NULL;
	//
	// As usual, check the "device" pointer to be sure it is
	// really interrupting.
	// Then assign "struct device *dev"
	//
	struct net_device *dev = (struct net_device *)dev_id;
	// ... and check with hw if it's really ours 

	// paranoid
	if (!dev)
		return;

	// Lock the device 
	priv = netdev_priv(dev);
	spin_lock(&priv->lock);

	// retrieve statusword: real netdevices use I/O instructions 
	statusword = priv->status;
	priv->status = 0;
	if (statusword & SETH_RX_INTR) {
		// send it to snull_rx for handling 
		seth_rx(dev, &dummy_pkt);
		
	}
	if (statusword & SETH_TX_INTR) {
		// a transmission is over: free the skb 
		priv->stats.tx_packets++;
		priv->stats.tx_bytes += 200;
		dev_kfree_skb(priv->skb);
	}
	
	// Unlock the device and we are done 
	spin_unlock(&priv->lock);
//	if (pkt) snull_release_buffer(pkt); // Do this outside the lock! 
	return;
}

/*
 * A NAPI interrupt handler.
 */
static void snull_napi_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	/*int statusword;
	struct snull_priv *priv;

	//
	// As usual, check the "device" pointer for shared handlers.
	// Then assign "struct device *dev"
	//
	struct net_device *dev = (struct net_device *)dev_id;
	// ... and check with hw if it's really ours 

	// paranoid 
	if (!dev)
		return;

	// Lock the device 
	priv = netdev_priv(dev);
	spin_lock(&priv->lock);

	// retrieve statusword: real netdevices use I/O instructions 
	statusword = priv->status;
	priv->status = 0;
	if (statusword & SETH_RX_INTR) {
		snull_rx_ints(dev, 0); // Disable further interrupts 
		///////netif_rx_schedule(dev);
	}
	if (statusword & SETH_TX_INTR) {
        	// a transmission is over: free the skb 
		priv->stats.tx_packets++;
		priv->stats.tx_bytes += priv->tx_packetlen;
		dev_kfree_skb(priv->skb);
	}

	// Unlock the device and we are done 
	spin_unlock(&priv->lock);
	*/
	return;
}



/*
 * Transmit a packet (low level interface)
 */
static int seth_hw_tx(char *buf, int len, struct net_device *dev)
{
	/*
	 * This function deals with hw details. This interface loops
	 * back the packet to the other snull interface (if any).
	 * In other words, this function implements the snull behaviour,
	 * while all other procedures are rather device-independent
	 */
	//struct iphdr *ih;
	//struct net_device *dest;
	struct seth_priv *priv;
	//u32 *saddr, *daddr;
//	struct snull_packet *tx_buffer;
    	int total,packets,err,res=0;

	/* I am paranoid. Ain't I? */
	if (len < sizeof(struct ethhdr) + sizeof(struct iphdr)) {
		printk("snull: Hmm... packet too short (%i octets)\n",
				len);
		return -1;
	}

	if (0) { /* enable this conditional to look at the data */
		int i;
		PDEBUG("len is %i\n" KERN_DEBUG "data:",len);
		for (i=14 ; i<len; i++)
			printk(" %02x",buf[i]&0xff);
		printk("\n");
	}
	priv = netdev_priv(dev);
//	priv->tx_packetlen = len;
//	priv->tx_packetdata = buf;
	KLOG("ifindex %d len %d sk :%x",priv->ifindex,len,priv->sk);
	//dev_kfree_skb(priv->skb);
	//return 0;
	total = ksend(priv->sk,(void *)buf, len,MSG_DONTWAIT,priv->ifindex);
	if (total != len){
		KLOG(" [%s] Failed TO transmit ... sent %d expected %d",dev->name,total,len);
		packets = 0;
		res = -1;
		err = 1;
	} else {
		packets = 1;
		err = 0;
		res = 0;
	}
//	priv->status |= SETH_TX_INTR;
/*	if (lockup && ((priv->stats.tx_packets + 1) % lockup) == 0) {
        	// Simulate a dropped transmit interrupt 
		netif_stop_queue(dev);
		PDEBUG("Simulate lockup at %ld, txp %ld\n", jiffies,
				(unsigned long) priv->stats.tx_packets);
	}*/
	//spin_lock(&priv->lock);
	priv->stats.tx_packets += packets;
	priv->stats.tx_bytes += total;
	priv->stats.tx_errors += err;
	//spin_unlock(&priv->lock);
	dev_kfree_skb(priv->skb);
	return res;
//	snull_interrupt(0, dev, NULL);
}

/*
 * Transmit a packet (called by the kernel)
 */
int seth_tx(struct sk_buff *skb, struct net_device *dev)
{
	int len;
	char *data, shortpkt[ETH_ZLEN];
	struct seth_priv *priv = netdev_priv(dev);
	KLOG("seth dummy TX : %d\n",skb->len);
	
	data = skb->data;
	len = skb->len;
	if (len < ETH_ZLEN) {
		memset(shortpkt, 0, ETH_ZLEN);
		memcpy(shortpkt, skb->data, skb->len);
		len = ETH_ZLEN;
		data = shortpkt;
	}
	dev->trans_start = jiffies; /* save the timestamp */

	/* Remember the skb, so we can free it at interrupt time */
	priv->skb = skb;

	/* actual deliver of data is device-specific, and not shown here */
	return seth_hw_tx(data, len, dev);

}

/*
 * Deal with a transmit timeout.
 */
void seth_tx_timeout (struct net_device *dev)
{
	struct seth_priv *priv = netdev_priv(dev);

	PDEBUG("Transmit timeout at %ld, latency %ld\n", jiffies,
			jiffies - dev->trans_start);
        /* Simulate a transmission interrupt to get things moving */
//	priv->status = SETH_TX_INTR;
//	snull_interrupt(0, dev, NULL);
	priv->stats.tx_errors++;
	netif_wake_queue(dev);
	return;
}



/*
 * Ioctl commands 
 */
int seth_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
	PDEBUG("ioctl\n");
	return 0;
}

/*
 * Return statistics to the caller
 */
struct net_device_stats *seth_stats(struct net_device *dev)
{
	struct seth_priv *priv = netdev_priv(dev);
	return &priv->stats;
}

/*
 * The "change_mtu" method is usually not needed.
 * If you need it, it must be like this.
 */
int seth_change_mtu(struct net_device *dev, int new_mtu)
{
	unsigned long flags;
	struct seth_priv *priv = netdev_priv(dev);
	spinlock_t *lock = &priv->lock;
    
	/* check ranges */
	if ((new_mtu < 68) || (new_mtu > 1500))
		return -EINVAL;
	/*
	 * Do anything you need, and the accept the value
	 */
	spin_lock_irqsave(lock, flags);
	dev->mtu = new_mtu;
	spin_unlock_irqrestore(lock, flags);
	return 0; /* success */
}

#ifdef HAVE_NET_DEVICE_OPS
static const struct net_device_ops seth_netdev_ops = {
        .ndo_open               = seth_open,
        .ndo_stop               = seth_release,
        .ndo_set_config         = seth_config,
        .ndo_start_xmit         = seth_tx,
        .ndo_get_stats          = seth_stats,
//      .ndo_set_multicast_list = snull_set_multi,
//      .ndo_set_mac_address    = snull_set_mac,
        .ndo_change_mtu         = seth_change_mtu,
        .ndo_do_ioctl           = seth_ioctl,
        .ndo_tx_timeout         = seth_tx_timeout,
//      .ndo_validate_addr      = eth_validate_addr,

//      .ndo_vlan_rx_register   = snull_vlan_rx_register,
 //     .ndo_vlan_rx_add_vid    = snull_vlan_rx_add_vid,
//      .ndo_vlan_rx_kill_vid   = snull_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
//        .ndo_poll_controller    = seth_poll,
#endif
};

#endif /* HAVE_NET_DEVICE_OPS */


/*
 * The init function (sometimes called probe).
 * It is invoked by register_netdev()
 */
void seth_init(struct net_device *dev)
{
	struct seth_priv *priv;
	struct net_device * net_dev = NULL;
#if 0
    	/*
	 * Make the usual checks: check_region(), probe irq, ...  -ENODEV
	 * should be returned if no device found.  No resource should be
	 * grabbed: this is done on open(). 
	 */
#endif

    	/* 
	 * Then, assign other fields in dev, using ether_setup() and some
	 * hand assignments
	 */
	ether_setup(dev); /* assign some of the fields */


#ifdef HAVE_NET_DEVICE_OPS
        dev->netdev_ops = &seth_netdev_ops;
#else
        dev->open            = seth_open;
        dev->stop            = seth_release;
        dev->set_config      = seth_config;
        dev->hard_start_xmit = seth_tx;
        dev->do_ioctl        = seth_ioctl;
        dev->get_stats       = seth_stats;
        dev->change_mtu      = seth_change_mtu;
//        dev->rebuild_header  = snull_rebuild_header;
//        dev->hard_header     = snull_header;
        dev->tx_timeout      = seth_tx_timeout;
//        netdev->set_multicast_list = &e1000_set_multi;
 //       netdev->set_mac_address = &e1000_set_mac;
//#ifdef HAVE_TX_TIMEOUT
 //       dev->tx_timeout = &seth_tx_timeout;
//#endif
#ifdef NETIF_F_HW_VLAN_TX
//      netdev->vlan_rx_register = e1000_vlan_rx_register;
 //     netdev->vlan_rx_add_vid = e1000_vlan_rx_add_vid;
 //     netdev->vlan_rx_kill_vid = e1000_vlan_rx_kill_vid;
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER

//      netdev->poll_controller = e1000_netpoll;
#endif
	dev->watchdog_timeo = timeout;
	if (use_napi) {
		dev->poll        = seth_poll;
		dev->weight      = 2;
	}
//	dev->hard_header_cache = NULL;      /* Disable caching */
#endif /* HAVE_NET_DEVICE_OPS */
	/* keep the default flags, just add NOARP */
//	dev->flags           |= IFF_NOARP;
//	dev->features        |= NETIF_F_NO_CSUM;

	/*
	 * Then, initialize the priv field. This encloses the statistics
	 * and a few private fields.
	 */
	priv = netdev_priv(dev);

	memset(priv, 0, sizeof(struct seth_priv));
	spin_lock_init(&priv->lock);
	net_dev = dev_get_by_name(&init_net,ifname);
	if (!net_dev)
	{
		KLOG("Failed to lookup %s ...\n",ifname);
		return;
	}
	priv->ifindex = net_dev->ifindex;
        KLOG("bind kernel socket to %s : %d\n",ifname,net_dev->ifindex);

	if( !(priv->sk = krsocket_open(ifname,dev->mtu,dev->mtu))){
		KLOG("Failed to initialize kernel raw socket\n");
		return;
	}	
//	seth_rx_ints(dev, 1);		/* enable receive interrupts */
	//snull_setup_pool(dev);
}

/*
 * The devices
 */

struct net_device *seth_devs[1];



/*
 * Finally, the module stuff
 */

void seth_cleanup(void)
{
	int i;
	struct seth_priv *priv;
    	KLOG(" seth_cleanup\n");
	for (i = 0; i < 1;  i++) {
		if (seth_devs[i]) {
			priv = netdev_priv(seth_devs[i]);
			unregister_netdev(seth_devs[i]);
			krsocket_close(priv->sk);
			//snull_teardown_pool(snull_devs[i]);
			free_netdev(seth_devs[i]);
		}
	}
	return;
}

/*
struct ethhdr hdr =  {
		.h_dest = "\0SAEED",
		.h_source = {0x00,0x11,0x22,0x33,0x44,0x55},
		.h_proto = htons(200)
	};
dummy_pkt.datalen = 200;
memcpy(dummy_pkt.data,&hdr,ETH_HLEN);
*/
int seth_init_module(void)
{
	int result, i, ret = -ENOMEM;
	KLOG(" seth_init_module\n");
	//snull_interrupt = use_napi ? snull_napi_interrupt : snull_regular_interrupt;
	seth_interrupt = seth_regular_interrupt;
	/* Allocate the devices */
	seth_devs[0] = alloc_netdev(sizeof(struct seth_priv), "seth%d",
			seth_init);
	if (seth_devs[0] == NULL )
		goto out;
	memcpy(seth_devs[0]->dev_addr, "\0SAEED", ETH_ALEN);
	ret = -ENODEV;
	for (i = 0; i < 1;  i++)
		if ((result = register_netdev(seth_devs[i])))
			printk("seth: error %i registering device \"%s\"\n",
					result, seth_devs[i]->name);
		else
			ret = 0;
   out:
	if (ret) 
		seth_cleanup();
	return ret;
}


module_init(seth_init_module);
module_exit(seth_cleanup);
